from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.shortcuts import render, get_object_or_404, redirect, HttpResponse
from django.views.decorators.http import require_POST
from django.urls import reverse

from conversation.models import Conversation
from .models import Category, Item, Cart, OrderItem, Order
from .forms import NewItemForm, EditItemForm, CartAddItemForm, OrderCreateForm


def items(request):
    query = request.GET.get('query', '')
    category_id = request.GET.get('category', 0)
    categories = Category.objects.all()
    items = Item.objects.filter(is_sold=False)

    if category_id:
        items = items.filter(category_id=category_id)

    if query:
        items = items.filter(Q(name__icontains=query) | Q(description__icontains=query))

    return render(request, 'item/items.html', {
        'items': items,
        'query': query,
        'categories': categories,
        'category_id': int(category_id)
    })


def detail(request, pk):
    item = get_object_or_404(Item, pk=pk)
    related_items = Item.objects.filter(category=item.category, is_sold=False).exclude(pk=pk)[0:3]

    conversation_exists = False
    if request.user.is_authenticated:
        conversation_exists = Conversation.objects.filter(item=item).filter(members__in=[request.user.id]).exists()

    return render(request, 'item/detail.html', {
        'item': item,
        'related_items': related_items,
        'conversation_exists': conversation_exists,
    })


@login_required
def new(request):
    if request.method == 'POST':
        form = NewItemForm(request.POST, request.FILES)

        if form.is_valid():
            item = form.save(commit=False)
            item.created_by = request.user
            item.save()

            return redirect('item:detail', pk=item.id)
    else:
        form = NewItemForm()

    return render(request, 'item/form.html', {
        'form': form,
        'title': '添加商品',
    })


@login_required
def edit(request, pk):
    item = get_object_or_404(Item, pk=pk, created_by=request.user)

    if request.method == 'POST':
        form = EditItemForm(request.POST, request.FILES, instance=item)

        if form.is_valid():
            form.save()

            return redirect('item:detail', pk=item.id)
    else:
        form = EditItemForm(instance=item)

    return render(request, 'item/form.html', {
        'form': form,
        'title': '修改商品',
    })


@login_required
def dashboard(request):
    items = Item.objects.filter(created_by=request.user)

    return render(request, 'item/dashboard.html', {'items': items})


def calc_cart_total_price(cart_items, discount=1):
    return sum((cart.item.price * cart.quantity) for cart in cart_items) * discount


@login_required
def cart_detail(request):
    cart_items = Cart.objects.filter(user=request.user, is_order=False)
    total_price = calc_cart_total_price(cart_items)
    return render(request, 'item/cart_detail.html',
                  {'cart_items': cart_items,
                   'total_price': total_price})


@login_required
def cart_add(request, item_id):
    item = Item.objects.filter(pk=item_id).first()
    if item and (item.created_by != request.user):
        cart_item = Cart.objects.filter(user=request.user, item=item).first()
        is_update = bool(cart_item)
        form = CartAddItemForm(request.POST or None, instance=cart_item)

        if request.method == 'POST':
            if form.is_valid():
                cart_item = form.save(commit=False)
                if cart_item.is_order:
                    cart_item.is_order = False
                    is_update = False
                    cart_item.quantity = 1
                if is_update:
                    cart_item.quantity +=1
                else:
                    cart_item.user = request.user
                    cart_item.item = item
                cart_item.save()
                return redirect('cart_detail')
    else:
        return HttpResponse(f'错误的 id {{ item_id }} 或者 不能添加自己的商品')
    return render(request, 'item/cart_add.html', {'item': item,
                                                  'form': form})


def cart_update(requset):
    # new quantity of item
    cart_id = requset.POST.get('cart_id')
    new_quantity = requset.POST.get('quantity')
    cart = Cart.objects.get(pk=cart_id)
    # update cart object
    cart.quantity = new_quantity
    cart.save()
    return redirect('cart_detail')

@login_required
@require_POST
def cart_delete(request, cart_id):
    cart = get_object_or_404(Cart, pk=cart_id)
    if request.user == cart.user:
        cart.delete()
        return redirect('cart_detail')
    else:
        return HttpResponse(f'错误的 cart id {{cart_id}}，不能删除')


@login_required
def checkout(request):
    cart_items = Cart.objects.filter(user=request.user, is_order=False)
    total_price = calc_cart_total_price(cart_items)
    form = OrderCreateForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        order = form.save(commit=False)
        order.user = request.user
        order.save()
        for cart in cart_items:
            OrderItem.objects.create(order=order, cart=cart)
        # clear carts
        cart_items.update(is_order=True)
        return redirect(reverse('order_detail', kwargs={'order_id': order.id}))

    return render(request, 'item/checkout.html',
                  {'cart_items': cart_items,
                   'total_price': total_price,
                   'form': form})


@login_required
def order_detail(request, order_id):
    order = get_object_or_404(Order, pk=order_id)
    return render(request, 'item/order.html', {'order': order})


@login_required
def order_list(request):
    order_items = OrderItem.objects.filter(cart__user=request.user)
    orders = Order.objects.filter(id__in=set(order_item.order.id
                                             for order_item in order_items))
    return render(request, 'item/order_list.html', {"orders": orders})
